package com.opennetexam.manager.controller;

import com.opennetexam.manager.exception.ComponentException;
import com.opennetexam.manager.common.CommonFunction;
import com.opennetexam.manager.utils.DateUtil;
import com.opennetexam.manager.utils.EncrptUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Map;

/**
 * @author 奶茶
 * Created on 2017/11/8.
 */
@Controller
@RequestMapping(value = "/ExamClient")
public class ExamClientController extends BaseController{

    private static Logger logger = Logger.getLogger(ExamClientController.class);

    /**
     * 获取客户端密码
     */
    @RequestMapping(value = "/GetOperPassword",method = RequestMethod.POST)
    public void getOperPassword(@RequestBody Map<String,String> requestBody,HttpServletResponse response) throws Exception {
        String sign = requestBody.get("sign");
        if(!("GetPassword").equals(sign)){
            throw new ComponentException("给定标识错误，获取密码失败！");
        }

        //获取当前系统时间
        String datetime = DateUtil.convertEncryptDateDayToString(new Date());
        //将当前日期加密
        String pwd = EncrptUtil.encodeMD5Hex(datetime);
        //再次加密
        pwd = EncrptUtil.encodeMD5Hex(pwd);
        //取加密后前八位
        String subPwd = pwd.substring(0, 8);
        CommonFunction.responseWrite(response,subPwd);
    }

    /**
     * 获取本机的局域网IP
     * @param response
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/GetLocalIP")
    public void getLocalIP(HttpServletRequest request, HttpServletResponse response) throws UnknownHostException {
        int remotePort = request.getServerPort();
        logger.info(remotePort);
        String hostAddress = InetAddress.getLocalHost().getHostAddress();
        CommonFunction.responseWrite(response,hostAddress);
    }
}
